package com.prs.crm.action.hr;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.courser.ui.TreeNode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.annotation.Clew;
import com.prs.crm.domain.hr.Role;
import com.prs.crm.domain.hr.ShareEim;
import com.prs.crm.domain.sys.Code;
import com.prs.crm.domain.sys.CodeCommon;
import com.prs.crm.domain.sys.Menu;
import com.prs.crm.domain.sys.Module;
import com.prs.crm.service.hr.RoleService;
import com.prs.crm.service.person.ShareEimService;
import com.prs.crm.service.sys.CodeCommonService;
import com.prs.crm.service.sys.CodeService;
import com.prs.crm.service.sys.MenuService;

public class RoleAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private Role role;

	private RoleService roleService;

	private PaginationSupport pagination;

	private Collection<Module> modules;

	private Collection<Menu> menus;

	private Collection<TreeNode> nodes;

	private Integer[] roleIds;

	private String menuId;

	private String uncheckId;

	private String moduleId;

	private Menu menu;

	private MenuService menuService;

	private CodeCommon codeCommon;
	private CodeCommonService codeCommonService;
	private String Encode;
	private Code code;
	private CodeService codeService;

	private Collection<CodeCommon> codelist;

	private Connection con;
	private Statement stmt;
	private ResultSet rs;
	private ResultSet rs1;
	private ResultSet rs2;
	private ResultSet rs3;
	private Statement stmt1;
	private Statement stmt2;
	private Statement stmt3;
	private Statement stmt4;
	private Statement stmt5;
	private Statement stmt6;
	private ShareEimService shareEimService;
	private String ClassName;
	private String userName;
	private String userPass;
	private String url1;
	private String address;
	private String baseName;
	public ShareEimService getShareEimService() {
		return shareEimService;
	}

	public void setShareEimService(ShareEimService shareEimService) {
		this.shareEimService = shareEimService;
	}

	public String getEncode() {
		return Encode;
	}

	public void setEncode(String encode) {
		Encode = encode;
	}

	public Role getRole() {
		return role;
	}

	public void setModules(Collection<Module> modules) {
		this.modules = modules;
	}

	public Collection<Module> getModules() {
		return modules;
	}

	public void setNodes(Collection<TreeNode> nodes) {
		this.nodes = nodes;
	}

	public Collection<TreeNode> getNodes() {
		return nodes;
	}

	public void setMenus(Collection<Menu> menus) {
		this.menus = menus;
	}

	public Collection<Menu> getMenus() {
		return menus;
	}

	public String getModuleId() {
		return moduleId;
	}

	public void setMenuId(String menuId) {
		this.menuId = menuId;
	}

	public String getMenuId() {
		return menuId;
	}

	public void setModuleId(String moduleId) {
		this.moduleId = moduleId;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public Integer[] getRoleIds() {
		return roleIds;
	}

	public void setRoleIds(Integer[] roleIds) {
		this.roleIds = roleIds;
	}

	@Action("listRole")
	public String execute() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Role.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getRoleService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}
	@Action("selectRoleMoive")
	public String selectRoleMoive() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Role.class);
		criteria.add(Restrictions.eq("busJud","电影"));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getRoleService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}
	@Action("selectRoleTiker")
	public String selectRoleTiker() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Role.class);
		criteria.add(Restrictions.eq("busJud","票务"));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getRoleService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}
	
	@Action("selectRole")
	public String selectRole() {
		this.execute();
		return SUCCESS;
	}
	@Action("selectBusinessRole")
	public String selectBusinessRole() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Role.class);
		criteria.add(Restrictions.eq("jud", "114"));
		criteria.add(Restrictions.eq("busJud", "114"));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getRoleService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("editRole")
	public String edit() {
		this.codelist = this.getCodeCommonService().getCodeCommonByCodeType(
				"职位");
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "saveRole", results = {
			@Result(name = "success", type = "redirect", location = "listRole"),
			@Result(name = "error", type = "chain", location = "editRole") })
	public String save() throws SQLException {
		if (role.getName() == null || "".equals(role.getName().trim())) {
			addActionError("名称不能为空");
			return ERROR;
		}
		if (role.getType() == null) {
			addActionError("类型不能为空");
			return ERROR;
		}
		if (role.getRolecode() == null || "".equals(role.getRolecode().trim())) {
			addActionError("编码不能为空");
			return ERROR;
		}

		if (role.getId() != null) {
			this.getRoleService().save(role);
		} else {
			if ("n".equals(Encode)) {
				int EncodeRplice = this.getCodeService().getBackRpliceAll(
						"手动编码", "职位", role.getRolecode());
				if (EncodeRplice != 0) {
					this.addActionError("编码重复!请重新输入");
					return ERROR;
				}
			}
			if ("n".equals(Encode)) {
				Code codes = new Code();
				codes.setCodeValue(role.getRolecode());
				codes.setEntityName(this.getClass().getName());
				codes.setCodeType("手动编码");
				codes.setCodeMolde("职位");
				this.getCodeService().save(codes);
				role.setCode(codes);
				role.setState(1);
				this.getRoleService().save(role);
			} else {
				CodeCommon Vob = this.getCodeCommonService().getVobject(
						codeCommon.getId());
				Code codes = new Code();
				codes.setEntityName(this.getClass().getName());
				codes.setCodeValue(role.getRolecode());
				Vob.setNumBackUp(Increase(Vob.getNumBackUp()));
				this.codeCommonService.saveOrUpdate(Vob);
				codes.setCodeType(Vob.getCodePlan());
				codes.setCodeMolde("职位");
				this.getCodeService().save(codes);
				role.setCode(codes);
				role.setState(1);
				this.getRoleService().save(role);
				
			}
		}
		
		this.setPrompt("提交职位成功");
		return SUCCESS;
	}

	@Action(value = "removeRole", results = {
			@Result(name = "success", type = "redirect", location = "listRole"),
			@Result(name = "error", type = "chain", location = "listRole") })
	public String remove() {
		if (roleIds == null) {
			this.addActionError("请选择要删除的职位");
			return ERROR;
		}
		for (Integer id : roleIds) {
			Role role = this.getRoleService().get(id);
			if (role.getPersons().size() != 0) {
				this.addActionError("已有客户引用，不能删除");
				return ERROR;
			}
		}
		this.getRoleService().batchRemove(this.getRoleIds());
		return SUCCESS;
	}

	/*
	 * @Action(value="grantPreview",results={@Result(name="success",type="json",params
	 * ={"root","prompt"})}) public String grantPreview() { if (moduleId!=null)
	 * { this.getRoleService().grant(role, moduleId.split(",")); }
	 * this.setPrompt("success"); return SUCCESS; }
	 */

	@Action(value = "grantPruview", results = { @Result(name = "success", type = "json", params = {
			"root", "prompt" }) })
	public String grantPruview() {
		if (menuId != null) {
			this.getRoleService().grantMenu(role, menuId.split(","));
		}
		this.setPrompt("success");
		return SUCCESS;
	}

	@Action(value = "grantPruviewByRootMenu", results = { @Result(name = "success", type = "json", params = {
			"root", "prompt" }) })
	public String grantPruviewByRootMenu() {
		if (menuId != null && uncheckId != null) {
			this.getRoleService().grantMenuByRootMenu(role, menu,
					menuId.split(","), uncheckId.split(","));
		}
		this.setPrompt("success");
		return SUCCESS;
	}

	@Action(value = "loadRole", results = { @Result(name = "success", type = "json", params = {
			"root", "modules", "excludeProperties", "resources" }) })
	public String loadRole() {
		this.setModules(role.getModules());
		return SUCCESS;
	}

	@Action("grantPurview")
	public String grantPurview() {
		return SUCCESS;
	}

	@Action(value = "loadRoleMenus", results = { @Result(name = "success", type = "json", params = {
			"root", "nodes" }) })
	public String loadRoleMenus() {
		if (role.getMenus() != null) {
			nodes = new ArrayList<TreeNode>();
			for (Menu menu : role.getMenus()) {
				TreeNode node = new TreeNode();
				node.setId(menu.getId().toString());
				node.setText(node.getText());
				nodes.add(node);
			}
		}
		return SUCCESS;
	}

	@Action("listRootMenu")
	public String listRootMenu() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Menu.class);
//		criteria.add(Restrictions.eq("text", "首页"));
		criteria.add(Restrictions.isNull("parent"));
		criteria.addOrder(Order.asc("sequence"));
		pagination = getPaginationHelper().prepare(pagination);
		this.setPagination(this.getRoleService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action(value = "loadChildTree")
	public String loadChildTree() {
		return SUCCESS;
	}

	@Action("viewRole")
	public String view() {
		return SUCCESS;
	}

//	@Action("editRoleShare")
//	public String editRoleShare(){		
//		return SUCCESS;
//	}
//
//	@Action(value = "saveColumn", results = {
//			@Result(name = "success", type = "redirect", location = "editRoleShare?role=${role.getId()}"),
//			@Result(name = "error", type = "chain", location = "editRoleShare") })
//	public String saveColumn() throws SQLException{
//		role.setAllfieldname("");
//		this.getRoleService().submit(role);
//		Properties pro=new Properties();
//		
//		String path = Thread.currentThread().getContextClassLoader().getResource("connect.properties").getPath();
//		try {
//			pro.load(new FileInputStream(path));
//		} catch (FileNotFoundException e1) {
//			e1.printStackTrace();
//		} catch (IOException e1) {
//			e1.printStackTrace();
//		}
//		String ClassName=pro.getProperty("ClassName");
//		String userName=pro.getProperty("userName");
//		String userPass=pro.getProperty("userPass");
//		String url1=pro.getProperty("url1");
//		try {
//			Class.forName(ClassName);
//			con = DriverManager.getConnection(url1, userName, userPass);
//			stmt = this.con.createStatement();
//			try{
//				PreparedStatement pst = con.prepareStatement("select * from "+role.getTableName());
//				rs1=pst.executeQuery();
//			}catch (Exception e) {
//				this.addActionError("请确认表名是否输入正确");
//				return ERROR;
//			}
//			ResultSetMetaData metaData = rs1.getMetaData();
//			 if (rs1.next()) {
//				 for (int i = 1; i <= metaData.getColumnCount(); i++) {
//				    if (role.getAllfieldname()==null || "".equals(role.getAllfieldname().trim())) {
//				    	role.setAllfieldname(metaData.getColumnName(i));
//					}else{
//						role.setAllfieldname(role.getAllfieldname()+","+metaData.getColumnName(i));
//					}
//				    this.getRoleService().submit(role);
//				 } 	
//			 }
//			 rs1.close();
//			 con.close();
//		} catch (ClassNotFoundException e) {
//			e.printStackTrace();
//		}
//		
//		return SUCCESS;
//	}
//	@Clew(results = { "success" })
//	@Action(value = "saveShare", results = {
//			@Result(name = "success", type = "redirect", location = "listRole"),
//			@Result(name = "error", type = "chain", location = "editRoleShare") })
//	public String saveShare() throws SQLException{
//		role.setState(2);
//		this.getRoleService().submit(role);
//		this.saveEimRole(role);
//		this.setPrompt("共享成功！");
//		return SUCCESS;
//	}
	public MenuService getMenuService() {
		return menuService;
	}

	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	public Menu getMenu() {
		return menu;
	}

	public void setMenu(Menu menu) {
		this.menu = menu;
	}

	public String getUncheckId() {
		return uncheckId;
	}

	public void setUncheckId(String uncheckId) {
		this.uncheckId = uncheckId;
	}

	public CodeCommon getCodeCommon() {
		return codeCommon;
	}

	public void setCodeCommon(CodeCommon codeCommon) {
		this.codeCommon = codeCommon;
	}

	public CodeCommonService getCodeCommonService() {
		return codeCommonService;
	}

	public void setCodeCommonService(CodeCommonService codeCommonService) {
		this.codeCommonService = codeCommonService;
	}

	public Code getCode() {
		return code;
	}

	public void setCode(Code code) {
		this.code = code;
	}

	public CodeService getCodeService() {
		return codeService;
	}

	public void setCodeService(CodeService codeService) {
		this.codeService = codeService;
	}

	public Collection<CodeCommon> getCodelist() {
		return codelist;
	}

	public void setCodelist(Collection<CodeCommon> codelist) {
		this.codelist = codelist;
	}

	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	public static String Increase(String backupNum) {
		String Inc = "";
		int lengths = backupNum.length();
		String lengthss = (Integer.parseInt(backupNum) + 1) + "";
		int increase = (lengthss.trim()).length();
		if (lengths != increase) {
			String In = "";
			for (int i = 0; i < lengths - increase; i++) {
				In = In + "0";
			}
			In = (In + lengthss).trim();
			Inc = In;
		} else {
			Inc = lengthss;
		}
		return Inc.trim();
	}
	public void saveEimRole(Role role) throws SQLException{
		ShareEim se=this.getShareEimService().getCode("se01");
		if (se!=null) {
			ClassName=se.getClassName();
			userName=se.getUserName();
			userPass=se.getUserPass();
			address=se.getIp();
			baseName=se.getBaseName();
			url1="jdbc:mysql://"+address+":3306/"+baseName;
		}
		try {
			Class.forName(ClassName);
			try {
				con = DriverManager.getConnection(url1, userName, userPass);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				stmt = this.con.createStatement();
				stmt1 = this.con.createStatement();
				stmt2 = this.con.createStatement();
				stmt3 = this.con.createStatement();
				stmt4 = this.con.createStatement();
				stmt5 = this.con.createStatement();
				stmt6 = this.con.createStatement();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			rs=stmt.executeQuery("select * from hr_role where name='"+role.getName()+"'");
			if(!rs.next()){
				rs1=stmt2.executeQuery("select * from hr_role_type where name='"+role.getType().getName()+"'");
				if(!rs1.next()){
					String sql2 = "insert into hr_role_type(name) values ("+"'"+role.getType().getName()+"'"+")";
					stmt3.executeUpdate(sql2);
					rs2=stmt4.executeQuery("select * from hr_role_type where name='"+role.getType().getName()+"'");
					while (rs2.next()) {
						String ids=rs2.getString("id");	
						String sql3 = "insert into hr_role(name,rolecode,type_id) values ("+"'"+role.getName()+"'"+",'"+role.getRolecode()+"'"+",'"+ids+"'"+")";
						stmt5.executeUpdate(sql3);
					}
					rs2.close();
				}
				else{
					rs3=stmt6.executeQuery("select * from hr_role_type where name='"+role.getType().getName()+"'");
					while (rs3.next()) {
						String ids1=rs3.getString("id");
						String sql1 = "insert into hr_role(name,rolecode,type_id) values ("+"'"+role.getName()+"'"+",'"+role.getRolecode()+"'"+",'"+ids1+"'"+")";
						stmt1.executeUpdate(sql1);
					}
					rs3.close();
				}
				rs1.close();
				con.close();
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
